//
// Create by Zeng Yun on 2019/2/2
//
// 管理服务器

package home

import (
	"adai.design/jarvis/device"
	"adai.design/jarvis/home/model"
	"adai.design/jarvis/member"
)

type ServiceManager struct {
	services []*model.Service
}

// 门磁变化推送
func (sm *ServiceManager) handleContactSensorNotify(h *Home, s *model.Service, char *model.Characteristic) {
	title := h.instance.Name
	subtitle := h.getRoomNameById(s.Room) + "的" + s.Name
	if value, _ := model.ToIntValue(char.Value); value != 0 {
		subtitle += "关闭了"
	} else {
		subtitle += "打开了"
	}
	push := &member.APNSAlert{
		Title: title,
		Body:  subtitle,
	}
	h.pushNotificationToMembers(push)
}

// 运动检测变化推送
func (sm *ServiceManager) handleMotionSensorNotify(h *Home, s *model.Service, char *model.Characteristic) {
	// 人体运动传感器，第一个数属性为人体探测值
	if char.CId != 1 {
		return
	}
	title := h.instance.Name
	subtitle := h.getRoomNameById(s.Room) + "的" + s.Name + "检测到"
	if value, _ := model.ToIntValue(char.Value); value != 0 {
		subtitle += "有人"
	} else {
		subtitle += "无人"
	}
	push := &member.APNSAlert{
		Title: title,
		Body:  subtitle,
	}
	h.pushNotificationToMembers(push)
}

func (sm *ServiceManager) handleAccessoryStateChanged(h *Home, aid, devType string, state string) {
	title := h.instance.Name
	var service *model.Service
	for _, s := range sm.services {
		if s.AId == aid && s.Type == devType {
			service = s
			break
		}
	}
	subtitle := h.getRoomNameById(service.Room) + "的" + service.Name
	if state == device.ContainerStateOffline {
		subtitle += "离线了"
	} else if state == device.ContainerStateOnline {
		subtitle += "上线了"
	}
	push := &member.APNSAlert{
		Title: title,
		Body:  subtitle,
	}
	h.pushNotificationToMembers(push)
}

func (sm *ServiceManager) CheckNotify(h *Home, char *model.Characteristic) {
	for _, s := range sm.services {
		if s.AId == char.AId && s.SId == char.SId && s.Notify {
			switch s.Type {

			// 门磁推送
			case model.TypeContactSensor:
				sm.handleContactSensorNotify(h, s, char)

			case model.TypeMotion:
				sm.handleMotionSensorNotify(h, s, char)

			}
		}
	}
}
